#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include <time.h>
#include <ctype.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include "os_api.h"
#include "debug.h"
#include "usb.h"



#define _TASK_STACK_SIZE (1024*3)

static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;

static OSMsgQRef usbMsgQ = NULL;

typedef struct
{
    int len;
    UINT8 *data;
} usbParam;


void usbVbusStatusCb(UINT8 status)
{
    LOG_PRINTF("%s[%d]: status %d\n", __FUNCTION__, __LINE__, status);
}

void usbRecvCallback(UINT8 *recv_data, UINT32 recv_len)
{
    OSA_STATUS osa_status;
    usbParam usb_data = {0};

    char *tempbuf = (char *)malloc(recv_len + 1);
    memset(tempbuf, 0x0, recv_len + 1);
    memcpy(tempbuf, (char *)recv_data, recv_len);

    usb_data.data = (UINT8 *)tempbuf;
    usb_data.len = recv_len;

    osa_status = OSAMsgQSend(usbMsgQ, sizeof(usbParam), (UINT8 *)&usb_data, OSA_NO_SUSPEND);
    ASSERT(osa_status == OS_SUCCESS);
}


static void usb_thread(void *param)
{
    usbParam usb_temp;
    OSA_STATUS status;

    hal_UsbOpenCb(USB_PORT_1, usbRecvCallback); 

    LOG_PRINTF("%s\n", __FUNCTION__);

    while (1)
    {
        memset(&usb_temp, 0, sizeof(usbParam));
        status = OSAMsgQRecv(usbMsgQ, (UINT8 *)&usb_temp, sizeof(usbParam), OSA_SUSPEND); // recv data from usb
        if (status == OS_SUCCESS)
        {
            if (usb_temp.data)
            {
                LOG_PRINTF("%s[%d]: usb_temp len:%d, data:%s\n", __FUNCTION__, __LINE__, usb_temp.len, (char *)(usb_temp.data));

                hal_UsbWrite(USB_PORT_1, (UINT8 *)usb_temp.data, usb_temp.len);

                free(usb_temp.data);
            }
        }
    }
}


int main(void)
{
    OSA_STATUS status;

    hal_UsbRegisterVbusCb(usbVbusStatusCb); // 注册USB插拔回调函数

    // hal_UsbSetNetType(0);     // 禁用网卡
    // hal_UsbSetNetType(1);     // 使用rndis网卡（默认值），如果需要使用rndis网卡，默认可以不设置
    // hal_UsbSetNetType(2);     // 使用ecm网卡

    LOG_PRINTF("%s[%d]: starting...\n", __FUNCTION__, __LINE__);
    status = OSAMsgQCreate(&usbMsgQ, "usbMsgQ", sizeof(usbParam), 300, OS_FIFO);
    ASSERT(status == OS_SUCCESS);

    status = OSATaskCreate(&_task_ref, _task_stack, _TASK_STACK_SIZE, 161, "usb_thread", usb_thread, NULL);
    ASSERT(status == OS_SUCCESS);

    return 0;
}
